const toc = require("markdown-toc");

module.exports = (info) => {
    const result = toc(info.markdownContent).json;

    function transfer(flatArr) {
        function createTOCItem(item){
            return {
                name: item.content,
                anchor: item.slug,
                level: item.lvl,
                children: []
            }
        }

        function handleItem(item){
            const top = stack[stack.length - 1];
            if(!top){
                stack.push(item);
            }else if(top.level < item.level){
                top.children.push(item);
                stack.push(item);
            }else{
                stack.pop();
                handleItem(item);
            }
        }

        const stack = [];
        const result = [];
        let min = 6;
        for (const item of flatArr) {
            if (min > item.lvl) {
                min = item.lvl;
            }
        }

        for (const item of flatArr) {
            const tocItem = createTOCItem(item);
            if(tocItem.level === min){
                result.push(tocItem);
            }
            handleItem(tocItem);
        }

        return result;
    }

    info.toc = transfer(result);

    delete info.markdownContent;

    for(const item of result){
        switch(item.lvl){
            case 1: {
                const str = `<h1 id="${item.slug}">`;
                info.htmlContent = info.htmlContent.replace("<h1>", str);
                break;
            }
            case 2: {
                const str = `<h2 id="${item.slug}">`;
                info.htmlContent = info.htmlContent.replace("<h2>", str);
                break;
            }
            case 3: {
                const str = `<h3 id="${item.slug}">`;
                info.htmlContent = info.htmlContent.replace("<h3>", str);
                break;
            }
            case 4: {
                const str = `<h4 id="${item.slug}">`;
                info.htmlContent = info.htmlContent.replace("<h4>", str);
                break;
            }
            case 5: {
                const str = `<h5 id="${item.slug}">`;
                info.htmlContent = info.htmlContent.replace("<h5>", str);
                break;
            }
            case 6: {
                const str = `<h6 id="${item.slug}">`;
                info.htmlContent = info.htmlContent.replace("<h6>", str);
                break;
            }
        }
    }

    return info;
}